package com.isias.system.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.isias.common.result.ResultCodeEnum;
import com.isias.model.system.SysUser;
import com.isias.system.custom.CustomUser;
import com.isias.system.mapper.SysMenuMapper;
import com.isias.system.mapper.SysUserMapper;
import com.isias.system.service.SysMenuService;
import com.isias.system.service.SysUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Component
@Transactional(rollbackFor = Exception.class)
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper mapper;

    @Autowired
    private SysMenuService sysMenuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //通过用户名来获取用户全部信息
        LambdaQueryWrapper<SysUser> infolqw = new LambdaQueryWrapper<>();
        //通过username查询到用户所有的信息
        infolqw.eq(SysUser::getUsername,username);
        SysUser sysUser = mapper.selectOne(infolqw);
        if (null == sysUser){
            throw new UsernameNotFoundException("用户不存在");
        }
        if (sysUser.getStatus() == 0){
            throw new RuntimeException("用户被禁用了");
        }
        //根据userid查询操作权限的数据
        List<String> buttonList = sysMenuService.getUserButtonList(sysUser.getId());
        //转换成security要求格式数据
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String s : buttonList) {
            authorities.add(new SimpleGrantedAuthority(s.trim()));  //去空格后转换为SimpleGrantedAuthority添加到authorities里
        }


        return new CustomUser(sysUser, authorities);

    }
}
